package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.TravelCondition;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.repository.TravelRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional  暂时先别管事务
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IUserInfoRedisService redisService;

    public Travel get(String id) {
        Optional<Travel> optional = repository.findById(id);
        if(optional.isPresent()){
            Travel travel = optional.get();
            travel.setAuthor(userInfoService.findById(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
            return travel;
        }
        return null;
    }

    //查询出页面结果集
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();
        TravelCondition day = qo.getDay();
        TravelCondition expend = qo.getExpend();
        if(qo.getState()==1){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_WAITING));
        }else if(qo.getState()==-1){
            query.addCriteria(Criteria.where("state").is(Travel.STATE_REJECT));
        }
        if(day!=null){
            query.addCriteria(Criteria.where("day").lte(day.getMax()).gte(day.getMin()));
        }
        if(expend!=null){
            query.addCriteria(Criteria.where("perExpend").lte(expend.getMax()).gte(expend.getMin()));
        }
        String orderType=null;
        PageRequest pr=null;
        if(TravelQuery.ORDER_NEW==qo.getOrderType()){
            orderType="CreateTime";
        }else if(TravelQuery.ORDER_HOT==qo.getOrderType()){
            orderType="viewnum";
        }
        pr = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, orderType);
        Page<Travel> page=DBHelper.query(template, Travel.class, query,pr);
        for(Travel travel:page){
            travel.setAuthor(userInfoService.findById(travel.getUserId()));
        }
        return page;
    }

    public void delete(String id) {
        repository.deleteById(id);
    }


    @Override
    public List<Travel> list() {
        return repository.findAll();
    }

    @Override
    public List<Travel> viewnumTop3(String destId) {
        PageRequest pr = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        return repository.findByDestId(destId,pr);
    }

    @Override
    public void changeState(String id, int state) {
        //判断是否有这篇游记
        //当游记状态为待发布时，执行审核操作
        // 审核通过，更改游记状态为审核通过  设置发布时间，设置最近修改时间
        //审核不通过，更改游记状态为审核不通过，设置修改时间 不设置发布时间
        // 执行下架操作，同审核拒绝操作
        Travel travel = this.get(id);
        if(travel!=null && (travel.getState()== Travel.STATE_WAITING || travel.getState()==Travel.STATE_RELEASE)){
            if(state==Travel.STATE_RELEASE){
                travel.setState(state);
                travel.setReleaseTime(new Date());
                travel.setLastUpdateTime(new Date());
            }else if(state==Travel.STATE_REJECT){
                travel.setState(state);
                travel.setReleaseTime(null);
                travel.setLastUpdateTime(new Date());
            }
        }
       repository.save(travel);
    }

    @Override
    public void update(Travel travel,HttpServletRequest request) {
        this.save(travel,request);
    }

    @Override
    public void save(Travel travel,HttpServletRequest request) {
        //destname
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());
        //userId
        String token = request.getHeader("token");
        UserInfo user = redisService.getUserByToken(token);
        travel.setUserId(user.getId());
        //createtime
        travel.setCreateTime(new Date());
        //lastupdatetime
        travel.setLastUpdateTime(new Date());
        //releasetime
        travel.setReleaseTime(new Date());
        repository.save(travel);
    }

    @Override
    public List<Travel> findByDestName(String destName) {
        List<Travel>  list=repository.findByDestName(destName);
        for (Travel travel : list) {
            travel.setAuthor(userInfoService.findById(travel.getUserId()));
        }
        return list;
    }

}
